//
//  ValidationErrorBehavior.swift
//  TuJiaMerchant
//
//  Created by 何海涛 on 16/1/7.
//  Copyright © 2016年 途家. All rights reserved.
//

import Foundation

@objc public protocol ValidationErrorBehaviorProtocol {
    func handleError(errors: [ValidationResult])
}

/// Do nothing
public class EmptyErrorBehavior : NSObject, ValidationErrorBehaviorProtocol {
    
    public func handleError(errors: [ValidationResult]) {
        // easy for test
        #if DEBUG
            ValidationErrorBehaviors.Print.handleError(errors: errors)
        #endif
        // do nothing.
    }
}

/// Show alert when model bind invalid, and focus if indeed.
public class AlertErrorBehavior : NSObject, ValidationErrorBehaviorProtocol {
    
    public func handleError(errors: [ValidationResult]) {
        // easy for test
        #if DEBUG
            ValidationErrorBehaviors.Print.handleError(errors: errors)
        #endif
        
//        if let first = errors.first {
//            TuJiaAutoLayoutPopupView.showAlert(text: first.errorMessage) { () -> Bool in
//                first.mapping?.views?.first?.becomeFirstResponder()
//                return true
//            }
//        }
    }
    
    public func handleErrorWithToast(errors:[ValidationResult]) {
//        if let first = errors.first {
//            TJToast.showMessage(first.errorMessage, duration: 1)
//        }
    }
    
}

public class PrintErrorBehavior : NSObject, ValidationErrorBehaviorProtocol {
    
    public func handleError(errors: [ValidationResult]) {
        
        for error in errors {
            print(error.memberName)
            print(error.errorMessage)
        }
    }
}

public class ShakeErrorBehavior : NSObject, ValidationErrorBehaviorProtocol {
    
    var shakeEnabled: Bool = true
    init(shake: Bool = true) {
        shakeEnabled = shake
    }
    
    public func handleError(errors: [ValidationResult]) {
        if let first = errors.first {
            if let view = first.mapping?.views?.first {
                view.shakeOff(first.errorMessage, shake: shakeEnabled)
            }
        }
    }
}

public class ValidationErrorBehaviors {
    public static let Empty = EmptyErrorBehavior()
    public static let Default = AlertErrorBehavior()
    public static let Print = PrintErrorBehavior()
    public static let Shake = ShakeErrorBehavior(shake: true)
    public static let ShakeOff = ShakeErrorBehavior(shake: false)
}
